package com.caifu.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caifu.bean.Result;
import com.caifu.bean.ResultEnum;
import com.caifu.bean.ResultUtil;
import com.caifu.exception.CustomException;
import com.caifu.mapper.SysOrganizationMapper;
import com.caifu.mapper.SysUserDataAuthMapper;
import com.caifu.mapper.SysUserRoleMapper;
import com.caifu.pojo.SysOrganization;
import com.caifu.pojo.SysUser;
import com.caifu.pojo.SysUserDataAuth;
import com.caifu.pojo.SysUserRole;
import com.caifu.util.CheckUtil;
import com.caifu.util.TreeUtils;
import com.caifu.util.UserUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author tww
 * ClassName: SysOrganizationService.java、
 * createTime: 2021年03月02日 10:04:29
 **/
@Service
@Transactional(rollbackFor = RuntimeException.class)
public class SysOrganizationService {

    @Resource
    private SysOrganizationMapper sysOrganizationMapper;

    @Resource
    private SysUserRoleMapper sysUserRoleMapper;

    @Resource
    private SysUserDataAuthMapper sysUserDataAuthMapper;


    public Result save(SysOrganization sysOrganization) {
        //顶级节点
        int lv = 0;
        //判断名称是否重复
        if (isExist(sysOrganization.getName())) {
            throw new CustomException(ResultEnum.NAME_ALREADY_EXISTS);
        }
        //判断是否为顶级节点
        if (lv == (sysOrganization.getPid())) {
            sysOrganization.setAncestors("0");
        } else {
            SysOrganization father = sysOrganizationMapper.selectById(sysOrganization.getPid());
            sysOrganization.setAncestors(father.getAncestors() + "," + father.getId());
        }
        sysOrganization.setCreatedTime(new Date());
        sysOrganization.setUpdatedTime(new Date());
        sysOrganization.setStatus("1");
        sysOrganizationMapper.insert(sysOrganization);

        return ResultUtil.success(0, "保存成功");
    }


    public Result update(SysOrganization sysOrganization) {
        SysOrganization newParentOrg = sysOrganizationMapper.selectById(sysOrganization.getPid());
        SysOrganization oldOrg = sysOrganizationMapper.selectById(sysOrganization.getId());
        //判断名称是否重复
        if (!oldOrg.getName().equals(sysOrganization.getName()) && isExist(sysOrganization.getName())) {
            throw new CustomException(ResultEnum.NAME_ALREADY_EXISTS);
        }

        //判断当前组织是否存在用户数据
        if (isExistUser(sysOrganization.getId())) {
            throw new CustomException(ResultEnum.NOT_ALLOWED_UPDATE);
        }

        //新的祖籍
        String newAncestors = "";
        if (CheckUtil.isNotNull(newParentOrg)) {
            newAncestors = newParentOrg.getAncestors() + "," + newParentOrg.getId();
        } else if (CheckUtil.isNull(newParentOrg)) {
            newAncestors = "0";
        }

        //旧祖籍
        String oldAncestors = oldOrg.getAncestors();
        sysOrganization.setAncestors(newAncestors);

        //修改子节点祖籍列表
        updateOrgChildren(sysOrganization.getId(), newAncestors, oldAncestors);

        sysOrganization.setCreatedTime(oldOrg.getCreatedTime());
        sysOrganization.setUpdatedTime(new Date());
        sysOrganization.setStatus("1");
        sysOrganizationMapper.updateById(sysOrganization);
        return ResultUtil.success(0, "保存成功");

    }

    /**
     * 修改子节点的祖籍
     *
     * @param id           被修改的节点id
     * @param newAncestors 新的祖籍列表
     * @param oldAncestors 旧的祖籍列表
     */
    private void updateOrgChildren(Integer id, String newAncestors, String oldAncestors) {
        String[] newAncestorsArr = newAncestors.split(",");

        // 查询当前节点所有子节点
        List<SysOrganization> childrenOrg = sysOrganizationMapper.selectChildrenOrgById(id);
        for (SysOrganization child : childrenOrg) {

            String replace = "";
            if ("0".equals(oldAncestors)) {
                String ancestors = child.getAncestors();
                String[] strings = ancestors.split(",");
                String[] duplication = duplication(newAncestorsArr, strings);
                Integer[] sort = sort(duplication);
                replace = StringUtils.join(sort, ",");
            } else {
                replace = child.getAncestors().replace(oldAncestors, newAncestors);
            }


            //判断子节点中是否有超过五级
            if (is_Beyond(replace)) {
                throw new CustomException(ResultEnum.NOT_ALLOWED_UPDATE_BEYOND);
            }

            child.setAncestors(replace);

            sysOrganizationMapper.updateById(child);
        }
    }

    /**
     * 判断节点是否超出5级
     *
     * @return
     */
    private boolean is_Beyond(String replace) {
        String[] split = replace.split(",");
        return split.length > 5;
    }


    /**
     * 判断组织机构下是否有用户数据
     *
     * @param id 组织机构id
     * @return
     */
    private boolean isExistUser(Integer id) {
        Integer orgId = sysUserDataAuthMapper.selectCount(new QueryWrapper<SysUserDataAuth>().eq("org_id", id));
        if (CheckUtil.isNotNull(orgId) && orgId > 0) {
            return true;
        }
        return false;
    }


    public List<SysOrganization> getOrgList(SysUser user) {
        //查询用户角色
        List<SysUserRole> userRoles = sysUserRoleMapper.selectList(new QueryWrapper<SysUserRole>().eq("user_id", user.getId()));
        //判断当前用户角色是不是管理员
        if (UserUtils.isAdmin(userRoles)) {
            List<SysOrganization> sysOrganizations = sysOrganizationMapper.selectList(new QueryWrapper<SysOrganization>()
                    .eq("status", 1));
            return TreeUtils.getChildPerms(sysOrganizations, 0);
        }
        List<SysOrganization> sysOrganizations = sysOrganizationMapper.selectOrgListByUserId(user.getId());
        return TreeUtils.getChildPerms(sysOrganizations, 0);
    }


    public List<SysOrganization> getAllOrgList() {
        List<SysOrganization> sysOrganizations = sysOrganizationMapper.selectList(new QueryWrapper<SysOrganization>()
                .eq("status", 1));
        return TreeUtils.getChildPerms(sysOrganizations, 0);
    }


    public Result deleteById(Integer nodeId) {
        //判断当前节点是否有子节点
        List<SysOrganization> sysOrganizations = sysOrganizationMapper.selectList(null);
        if (!TreeUtils.isEndNode(sysOrganizations, nodeId)) {
            throw new CustomException(ResultEnum.NOT_ALLOWED_DELETE);
        }

        //判断当前组织是否存在用户数据

        SysOrganization sysOrganization = sysOrganizationMapper.selectById(nodeId);
        sysOrganization.setStatus("9");
        sysOrganizationMapper.updateById(sysOrganization);

        return ResultUtil.success(200, "数据已删除");
    }


    /**
     * 判断组织名称是否存在
     */
    private boolean isExist(String name) {
        Integer count = sysOrganizationMapper.selectCount(new QueryWrapper<SysOrganization>().eq("name", name));
        if (CheckUtil.isNotNull(count) && count > 0) {
            return true;
        }
        return false;
    }


    public SysOrganization getOrgById(Integer orgId) {
        return sysOrganizationMapper.selectById(orgId);
    }

    public SysOrganization getPOrgById(SysOrganization org) {
        SysOrganization sysOrganization = sysOrganizationMapper.selectById(org.getId());
        return sysOrganizationMapper.selectById(sysOrganization.getPid());
    }

    public static void main(String[] args) {
        String[] first = {"1", "2", "234", "4", "5"};
        String[] second = {"8", "2", "4", "6"};
        //String[] replace = replace(first, second);

        String[] duplication = duplication(first, second);
        Integer[] sort = sort(duplication);

        String join = StringUtils.join(sort, ",");
        System.out.println("join = " + join);
    }

    private static String[] replace(String[] first, String[] second) {
        // 去重
        HashSet<String> hashSet = new HashSet<>();
        for (String aFirst : first) {
            hashSet.add(aFirst);
        }
        for (String aSecond : second) {
            hashSet.add(aSecond);
        }
        // 利用TreeSet排序
        Set<String> set = new TreeSet(hashSet);
        String[] integers = set.toArray(new String[]{});

        // 排序去重后的结果数组
        String[] result = new String[integers.length];
        for (int i = 0; i < integers.length; i++) {
            result[i] = integers[i];
        }
        return result;
    }

    /**
     * string 数组排序
     */
    private static Integer[] sort(String[] arr) {
        HashSet<Integer> hashSet = new HashSet<>();
        for (String s : arr) {
            hashSet.add(Integer.valueOf(s));
        }
        // 利用TreeSet排序
        Set<Integer> set = new TreeSet(hashSet);
        Integer[] integers = set.toArray(new Integer[]{});
        return integers;
    }


    /**
     * 数组去重
     *
     * @param first
     * @param second
     * @return
     */
    private static String[] duplication(String[] first, String[] second) {
        // 去重
        HashSet<String> hashSet = new HashSet<>();
        for (String aFirst : first) {
            hashSet.add(aFirst);
        }

        for (String aSecond : second) {
            hashSet.add(aSecond);
        }
        return hashSet.toArray(new String[]{});
    }


}


